package handels

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"tu-tu-manage/cache"
	"tu-tu-manage/models"
)

func FileOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var list []models.FileOrderList
	redis_key := "/list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.
			Select(
				"file_orders.id as OrderID",
				"files.file_name as FileName",
				"files.file_node as FileNode",
				"files.file_price as FilePrice",
				"file_orders.order_to as OrderTo",
				"file_orders.order_from as OrderFrom",
				"file_orders.order_text as OrderText",
			).
			Table("file_orders").
			Joins("LEFT JOIN files ON files.id = file_orders.fid").
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var count int64
	models.DB.Model(&models.FileOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})
	return
}
func FileOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var list models.FileOrderList
	redis_key := "/detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.
			Select(
				"file_orders.id as OrderID",
				"files.file_name as FileName",
				"files.file_node as FileNode",
				"files.file_price as FilePrice",
				"file_orders.order_to as OrderTo",
				"file_orders.order_from as OrderFrom",
				"file_orders.order_text as OrderText",
			).
			Table("file_orders").
			Joins("LEFT JOIN files ON files.id = file_orders.fid").
			Where("file_orders.id = ?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
